import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'


Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '',
    nextId: 5,
    // 选择 全部、已完成、未完成
    selectView: 'all'
  },
  mutations: {
    // 初始化数据
    initList(state, list) {
      state.list = list
    },
    // 修改input值
    changeInput(state, val) {
      state.inputValue = val
    },
    // 添加数据
    addItem(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue,
        done: false
      }
      state.nextId++
      state.list.push(obj)
      state.inputValue = ''
    },
    // 根据id删除数据
    removeItem(state, id) {
      const i = state.list.findIndex(item => item.id == id)
      if (i != -1)
        state.list.splice(i, 1)
    },
    // 根据id改变响应的done属性值
    changeDone(state, id) {
      const i = state.list.findIndex(item => item.id == id)
      if (i != -1)
        state.list[i].done = !state.list[i].done
    },
    // 清除已完成
    cleanDone(state) {
      state.list = state.list.filter(item => item.done == false)
    },
    // 修改selectView的值
    editSelect(state, type) {
      state.selectView = type
    }
  },
  actions: {
    async getData(context) {
      const {
        data: res
      } = await axios.get('/list.json')
      // axios.get('/list.json').then(({data}) => {
      //   console.log(data);
      // })
      console.log(res)
      context.commit('initList', res)
    }
  },
  modules: {},
  getters: {
    // 未完成的数量
    unDoneNum(state) {
      return state.list.filter(item => item.done == false).length
    },
    infolist(state) {
      if(state.selectView == 'undone') {
        return state.list.filter(item => item.done == false)
      }
      else if(state.selectView == 'done') {
        return state.list.filter(item => item.done)
      }
      else {
        return state.list
      }
    }
  }
})
